package systemcontroller

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"ruoyi-go/app/service"
	"ruoyi-go/app/token"
	"ruoyi-go/common/upload"
	"ruoyi-go/config"
	"ruoyi-go/framework/response"
	"strconv"
	"strings"
)

type FileController struct{}

// 文件下載
func (controller *FileController) Upload(ctx *gin.Context) {
	file, err := ctx.FormFile("file")
	if err != nil {
		panic(err)
	}
	open, err := file.Open()
	if err != nil {
		panic(err)
	}
	key := upload.PutFile(upload.GetKey(file.Filename), open)

	value, _ := ctx.Get(config.AuthUser)

	user := value.(*token.UserTokenResponse)
	(&service.FileService{}).SaveFileData(user,
		key, file.Filename)

	response.NewSuccess().SetData("path", key).Json(ctx)
}

// 文件下載
func (controller *FileController) Download(ctx *gin.Context) {
	path := ctx.Query("key")

	reader := upload.GetSmallFile(path)
	index := strings.LastIndexByte(path, '/')
	path = path[index+1:]

	// 设置下载 headers
	//ctx.Header("Content-Type", reader.ContentType)
	stat, err := reader.Stat()
	if err != nil {
		panic(err)
	}
	ctx.Header("Content-Type", stat.ContentType)
	ctx.Header("Content-Transfer-Encoding", "binary")
	ctx.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", path))
	ctx.Header("Content-Length", fmt.Sprintf("%d", stat.Size))

	io.Copy(ctx.Writer, reader)
	defer reader.Close()
}

func (controller *FileController) GetFileData(c *gin.Context) {
	value := c.Query("id")
	i, err := strconv.ParseInt(value, 10, 32)
	if err != nil {
		panic(err)
	}
	data := (&service.FileService{}).GetFileData(int32(i))

	response.NewSuccess().SetData("data", data).Json(c)

}
